﻿using UnityEngine;
using System.Collections;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour {
	/* * * * * * * 
	 * Properties
	 * * * * * * */
	private static string _name = "SingletonContainer";

	/* * * * * * * 
	 * Methods
	 * * * * * * */
	public void SetName(string n) {
		_name = n;
		if (_gameObject != null) _gameObject.name = _name;
	}

	void Awake() {
		if (_instance != null && _gameObject != null) {
			if (_instance != this) {
				Destroy (_gameObject);
			}
		}
	}

	/* * * * * * * 
	 * Static part
	 * * * * * * */
	private static GameObject _gameObject;
	private static T _instance;
	public static T Instance {
		get {
			if (_instance == null) {
				CreateInstance();
			}
			
			return _instance;
		}
	}

	private static void CreateInstance() {
		//check if gameobject is already created
		if (_gameObject == null) {
			//try to find a gameobject by name
			_instance = (T) GameObject.FindObjectOfType<T>();
			//nothing found, create a gameobject
			if (_instance == null) {
				_gameObject = new GameObject();
				_gameObject.name = _name;
				_instance = (T) _gameObject.AddComponent<T>();

				//dont destroy this on load
				DontDestroyOnLoad(_gameObject);
			} else {
				//gameobject found, set instance to component
				_gameObject = _instance.gameObject;
			}
		}
	}
}